package com.wq.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wq.dto.AdminLoginDTO;
import com.wq.entity.Admin;
import com.wq.mapper.AdminMapper;
import com.wq.service.AdminService;
import com.wq.utils.JwtUtil;
import com.wq.vo.AdminDetailVO;
import com.wq.vo.AdminLoginVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;



@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private HttpServletRequest request;
    @Resource
    private AdminDetailVO adminDetailVO;
    @Resource
    private AdminLoginVO adminLoginVO;
    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        log.info("加密后的密文：{}", BCrypt.hashpw(adminLoginDTO.getPassword()));
        //1-用adminLoginDTO传递进来的用户名去数据库中查询
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);
        //2.1-没有查到报错
        if(admin==null){
            throw new RuntimeException("用户名不存在或密码不正确");
        }
        //2.2-查到了就来比较密码
        //3.1-密码不正确报错
        if(!BCrypt.checkpw(adminLoginDTO.getPassword(),admin.getPassword())){
            throw new RuntimeException("用户名不存在或密码不正确");
        }
        //3.2-密码正确就返回token
        Claims claims= Jwts.claims();
        claims.put("id",admin.getId());
        //todo 秘钥是写死的，需要活的密钥
        String token=jwtUtil.createToken(claims);

        //4 - token怎么生成？
        adminLoginVO.setToken(token);
        return  adminLoginVO;
    }


    public AdminDetailVO detail() {
        //注入->request-> header->token->id
        String token = request.getHeader("authorization");
        //去掉Bearer前缀
        token = token.replace("Bearer ", "");
        log.info("token:{}",token);
        //解析token->直接解析有可能token已经过期，会抛异常->先检查，没过期再来解析
        if(!jwtUtil.validateToken(token)){
            throw new RuntimeException("token已过期");
        }
        Claims claims = jwtUtil.parseToken(token);
        //获取id，get()增加了字节码参数，避免类型转换异常
        Integer id = claims.get("id", Integer.class);
        Admin admin = this.getById(id);
        adminDetailVO.setUsername(admin.getUsername());
        return adminDetailVO;
    }
}
